import { useState, useEffect, useCallback } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import {getTopics} from '../api/cnode';
import axios from 'axios';
// 对象的属性名一定得是合法的标识符,不要用汉字作为key
const type = {
    all: '全部',
    good: '精华',
    share: '分享',
    ask: '问答',
    job: '招聘',
    dev: '客户端测试',
}

const Home = ({navigation}) => {
    const [currentTab, setCurrentTab] = useState('all');
    const [list, setList] = useState([]);
    // 开发成本、维护成本
    // 学会封装函数
    // 学会封装组件
    // 不要再用fetch
    useEffect(()=>{
        axios.get('https://cnodejs.org/api/v1/topics',{params:{tab: currentTab}})
            .then(res=>{
                setList(res.data.data)
            })
            .catch(err=>{
                console.log(err);
            })
    }, [currentTab])
    const TabItem = ({tab}) => {
        return (
            <Text
                onPress={() => setCurrentTab(tab)}
                style={[
                    styles.tab,
                    { backgroundColor: currentTab == tab ? '#f00' : '#fff' }
                ]}
            >{type[tab]}</Text>
        )
    }
    return (
        <View style={{flex: 1}}>
            <Text style={styles.tabContainer}>
                {
                    Object.keys(type).map(item => (
                        <TabItem key={item} tab={item} />
                    ))
                }
            </Text>
            <View>
                {
                    list.map(item=>{
                        return (
                            <View key={item.id}>
                                <Text>{item.title}</Text>
                                <Text>
                                    {type[item.tab]}
                                </Text>
                            </View>
                        )
                    })
                }
            </View>
        </View>
    )
}
export default Home

const styles = StyleSheet.create({
    tab:{
        fontSize: 30,
    }
})